package chapter01;

public class SearchRange {
    //二分法
    /**
     * 区间[l, r]划分成[l, mid]和[mid + 1, r]时，其更新操作是r = mid或者l = mid + 1;，计算mid时不需要加1。
     * 区间[l, r]划分成[l, mid - 1]和[mid, r]时，其更新操作是r = mid - 1或者l = mid;，此时为了防止死循环，计算mid时需要加1。
     */
    public int[] searchRange(int[] nums, int target) {
        if(nums==null||nums.length<1){
            return new int[]{-1,-1};
        }
        if(nums.length==1){
            return target==nums[0]?new int[]{0,0}:new int[]{-1,-1};
        }
        int length=nums.length;
        int left=findLeftIndex(nums,target);
        if(left==-1){
            return new int[]{-1,-1};
        }
        int right=findRightIndex(nums,target);
        return new int[]{left,right};
    }

    public int findLeftIndex(int[] nums, int target){
        int left=0;
        int right=nums.length-1;
        //小于等于会死循环
        while (left<right){
            int mid=left+(right-left)/2;
            if(nums[mid]>target){  //[left,mid-1]
                right=mid-1;
            }else if(nums[mid]==target){    //[left,mid]
                right=mid;
            }else{
                left=mid+1;   //[mid+1,right]
            }
        }
        if(nums[left]==target){
            return left;
        }
        return -1;
    }

    public int findRightIndex(int[] nums, int target){
        int left=0;
        int right=nums.length-1;
        while (left<right){
            int mid=(right+left+1)/2;
            if(nums[mid]>target){ //[left,mid-1]
                right=mid-1;
            }else if(nums[mid]==target){ //[mid,right]
                left=mid;
            }else{
                left=mid+1;  //[mid+1,right]
            }
        }
        return left;
    }
}
